package com.chen.pfm.slice;

import com.chen.pfm.ResourceTable;
import com.chen.pfm.entity.Account;
import com.chen.pfm.entity.ResultVo;
import com.chen.pfm.entity.User;
import com.chen.pfm.provider.TitleProvider;
import com.chen.pfm.utils.*;
import com.google.gson.Gson;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.ability.DataAbilityRemoteException;
import ohos.aafwk.content.Intent;
import ohos.agp.components.*;
import ohos.agp.utils.LayoutAlignment;
import ohos.agp.window.dialog.CommonDialog;
import ohos.agp.window.dialog.ListDialog;
import ohos.app.AbilityContext;
import ohos.app.dispatcher.task.TaskPriority;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;
import okhttp3.FormBody;
import okhttp3.RequestBody;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import static ohos.agp.components.ComponentContainer.LayoutConfig.MATCH_CONTENT;
import static ohos.agp.components.ComponentContainer.LayoutConfig.MATCH_PARENT;

public class UserInfoAbilitySlice extends AbilitySlice {
    static final HiLogLabel LABEL = new HiLogLabel(HiLog.LOG_APP, 0x2022001, "UserInfoAbilitySlice");

    Text userinfo_uid;
    Text userinfo_userid;
    Text userinfo_username;
    Text userinfo_gender;
    Text userinfo_grade;
    Text userinfo_birthday;
    Text userinfo_age;
    Text userinfo_createtime;
    User user;
    int dateYear;
    int dateMonth;
    int dateDay;
    String newBirthday;
    String newGender;
    String newUsername;
    Button save;//保存按钮
    int update;
    DirectionalLayout layout_username;
    DirectionalLayout layout_gender;
    DirectionalLayout layout_birthday;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_user_info);
        //返回按钮监听


        findComponentById(ResourceTable.Id_goback_btn).setClickedListener(component -> terminate());
        String struid = DataBaseUtil.GetValue(this, "uid");
        if (struid == null) {
            MyToast.showMyToast(this, "用户uid出错");
            return;
        }
        int uid = Integer.valueOf(struid);
        user = UserDBUtil.queryOneByUid(this, uid);
        newGender = user.getGender();
        newBirthday = user.getBirthday();
        newUsername = user.getUsername();
        HiLog.info(LABEL, "用户数据为：" + user.toString());
        //加载组件
        userinfo_uid = (Text) findComponentById(ResourceTable.Id_userinfo_uid);
        userinfo_userid = (Text) findComponentById(ResourceTable.Id_userinfo_userid);
        userinfo_username = (Text) findComponentById(ResourceTable.Id_userinfo_username);
        userinfo_gender = (Text) findComponentById(ResourceTable.Id_userinfo_gender);
        userinfo_grade = (Text) findComponentById(ResourceTable.Id_userinfo_grade);
        userinfo_birthday = (Text) findComponentById(ResourceTable.Id_userinfo_birthday);
        userinfo_age = (Text) findComponentById(ResourceTable.Id_userinfo_age);
        userinfo_createtime = (Text) findComponentById(ResourceTable.Id_userinfo_createtime);
        save = (Button) findComponentById(ResourceTable.Id_save);
        layout_username = (DirectionalLayout) findComponentById(ResourceTable.Id_layout_username);
        layout_gender = (DirectionalLayout) findComponentById(ResourceTable.Id_layout_gender);
        layout_birthday = (DirectionalLayout) findComponentById(ResourceTable.Id_layout_birthday);

        loadingData();

        //设置点击事件
        //用户昵称
        layout_username.setClickedListener(component -> {
            getInputFromTextTextField(this, "设置昵称", "请输入您的昵称", userinfo_username);
        });
        //性别
        layout_gender.setClickedListener(component -> showPickGenderType(this, component));
        //生日
        layout_birthday.setClickedListener(component -> showPickBirthday(this, component));
        //保存数据
        save.setClickedListener(component -> saveData(this, component));
    }

    //保存数据，更新远端数据
    private void saveData(AbilityContext context, Component component) {
        newUsername = userinfo_username.getText();
        update = 0;
        if (!newUsername.equals(user.getUsername())) {//需要更新昵称
            user.setUsername(newUsername);
            update++;
        }
        if (!newBirthday.equals(user.getBirthday())) {//需要更新生日
            user.setBirthday(newBirthday);
            update++;
        }
        if (!newGender.equals(user.getGender())) {//需要更新性别
            user.setGender(newGender);
            update++;
        }
        if (update == 0) {
            MyToast.showMyToast(this, "没有要更新的数据！");
            return;
        }

        try {
            int update = UserDBUtil.update(this, user);
            if (update > 0) {
                MyToast.showMyToast(this, "本地个人信息更新成功");
                //更新远程数据
                updateRemoteData(MyUtil.updateUser, user);
            }
        } catch (DataAbilityRemoteException e) {
            e.printStackTrace();
        }

    }

    private void updateRemoteData(String url, Object sendJsonObject) {

        //开一个线程更新用户信息
        getGlobalTaskDispatcher(TaskPriority.DEFAULT).asyncDispatch(() -> {
            ResultVo resultVo;
            String getRequestjson = null;
            Gson gson = new Gson();
            String sendjson = gson.toJson(sendJsonObject);
            //转化为json
            try {
                getRequestjson = HttpRequestUtil.sendPostRequestByOkHttp(url, sendjson);
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (getRequestjson == null || getRequestjson.contains("not found")) {
                HiLog.info(LABEL, "无法连接到网络！");
                //刷新页面上的数据，同样有一个坑，onChange方法实质上，在一个子线程里执行
                getUITaskDispatcher().asyncDispatch(() -> {
                            //在这里执行页面ui组件的显示刷新
                            MyToast.showMyToast(this, "无法连接到网络");
                        }
                );
                return;
            } else {
                try {
                    resultVo = gson.fromJson(getRequestjson, ResultVo.class);
                } catch (Exception e) {//这里必须用Exception接收
                    getUITaskDispatcher().asyncDispatch(() -> {
                        MyToast.showMyToast(this, "gson解析返回对象失败，请确定服务器是否开启");
                    });
                    HiLog.error(LABEL, "有网络但是连接不到服务器时返回数据为：" + getRequestjson);
                    return;
                }
                if (resultVo == null) {//返回对象进行解析
                    HiLog.info(LABEL, "返回对象为空！");
                    //刷新页面上的数据，同样有一个坑，onChange方法实质上，在一个子线程里执行
                    getUITaskDispatcher().asyncDispatch(() -> {
                        //在这里执行页面ui组件的显示刷新
                        MyToast.showMyToast(this, "返回为空,数据丢失！");
                    });
                } else {
                    getUITaskDispatcher().asyncDispatch(() -> {
                        //在这里执行页面ui组件的显示刷新
                        MyToast.showMyToast(this, "状态码" + resultVo.getCode() + " " + resultVo.getMsg());
                    });
                }
            }

        });

    }

    void loadingData() {
        getUITaskDispatcher().asyncDispatch(() -> {
            //渲染数据
            userinfo_uid.setText(String.valueOf(user.getUid()));
            userinfo_userid.setText(user.getUserid());
            userinfo_username.setText(user.getUsername());
            userinfo_gender.setText(user.getGender());
            userinfo_grade.setText(user.getGrade());
            userinfo_birthday.setText(DateUtils.getChineseFormatFromStr(user.getBirthday()));
            userinfo_age.setText(DateUtils.getAgeFromBirthday(user.getBirthday()));
            userinfo_createtime.setText(user.getCreatetime());
        });
    }

    private void getInputFromTextTextField(AbilityContext context, String Title, String hint, Text inputText) {
        //布局加载
        Component parse = LayoutScatter.getInstance(this).parse(ResourceTable.Layout_dialog_remark_layout_input, null, false);
        //标题
        Text title = (Text) parse.findComponentById(ResourceTable.Id_title);//创建显示气窗
        //输入框
        TextField textField = (TextField) parse.findComponentById(ResourceTable.Id_TextField);

        getUITaskDispatcher().asyncDispatch(() -> {//ui刷新线程显示


            //设置要渲染的输入框数据
            title.setText(Title);
            textField.setHint(hint);
            //将原来的文字放置到输入框中
            textField.setText(inputText.getText());
            //创建一个气窗
            CommonDialog dialog = new CommonDialog(this);
            //设置位置
            dialog.setOffset(0, 10);
            dialog.setContentCustomComponent(parse);
            dialog.setSize(MATCH_CONTENT, MATCH_CONTENT);
            //取消按钮
            Button cancel = (Button) parse.findComponentById(ResourceTable.Id_cancel);
            //确定按钮
            Button ok = (Button) parse.findComponentById(ResourceTable.Id_ok);


            dialog.show();
            cancel.setClickedListener(c -> {
                dialog.destroy();
                MyToast.showMyToast(this, "已取消");

            });
            ok.setClickedListener(c -> {//按下确定按钮
                String strTextField = textField.getText();//得到输入框的值
                //如果原的值和输入框的值不一样，就取新的值
                if (!inputText.getText().equals(strTextField)) {
                    inputText.setText(strTextField);
                }
                dialog.hide();

            });
        });
    }

    public void showPickGenderType(AbilityContext context, Component component) {
        //性别类型
        ListDialog listDialog = new ListDialog(context, ListDialog.SINGLE);
        listDialog.setCornerRadius(25);

        listDialog.setSize(800, MATCH_CONTENT);
        String[] strings = {"男", "女", "保密"};
        List<String> titles = new ArrayList<>();
        titles.add(strings[0]);
        titles.add(strings[1]);
        titles.add(strings[2]);
        //必须设计这个
        listDialog.setItems(strings);
        TitleProvider titleProvider = new TitleProvider(titles, this);
        listDialog.setProvider(titleProvider);
        listDialog.setButton(0, "取消", (iDialog, i) -> {
            iDialog.hide();
            MyToast.showMyToast(this, "已取消");

        });

        //展示
        listDialog.show();
        //监听
        ((ListContainer) listDialog.getListContainer()).setItemSelectedListener((listContainer, component1, i, l) -> {
            MyToast.showMyToast(this, "你选择了" + strings[i]);
            newGender = strings[i];
            userinfo_gender.setText(strings[i]);
            //改变渲染数据
            listDialog.hide();
        });
    }

    public void showPickBirthday(AbilityContext context, Component component) {
        //弹出日期dialog，选择日期
        getUITaskDispatcher().asyncDispatch(() -> {

            CommonDialog commonDialog = new CommonDialog(context);
            Component parse = LayoutScatter.getInstance(context)
                    .parse(ResourceTable.Layout_dialog_date_layout_confirm, null, false);
            DatePicker datePicker = (DatePicker) parse.findComponentById(ResourceTable.Id_date_pick);
            LocalDateTime localDateTime = LocalDateTime.now();
            datePicker.setMinDate(0);
            //以传递的小时数偏移量作为参数来获取ZoneOffset,设置时区,转换为自1970-01-01T00：00：00Z以来的秒,
            Long MaxDatesecond = localDateTime.toEpochSecond(ZoneOffset.of("+8"));
            datePicker.setMaxDate(MaxDatesecond);
            commonDialog.setSize(MATCH_CONTENT, MATCH_CONTENT);
            commonDialog.setAlignment(LayoutAlignment.CENTER);
            commonDialog.setTransparent(true);
            commonDialog.setCornerRadius(15);
            commonDialog.setContentCustomComponent(parse);
            commonDialog.show();
            //取消按钮
            Button cancel = (Button) parse.findComponentById(ResourceTable.Id_cancel);
            //确定按钮
            Button ok = (Button) parse.findComponentById(ResourceTable.Id_ok);
            cancel.setClickedListener(c -> {
                commonDialog.destroy();
                MyToast.showMyToast(this, "已取消");

            });
            ok.setClickedListener(c -> {
                dateYear = datePicker.getYear();
                dateMonth = datePicker.getMonth();
                dateDay = datePicker.getDayOfMonth();
                newBirthday = DateUtils.getStrDecimalFormatDate(dateYear, dateMonth, dateDay, 0, 0, 0);
                userinfo_age.setText(DateUtils.getAgeFromBirthday(newBirthday));
                userinfo_birthday.setText(DateUtils.getChineseFormatFromPicker(dateYear, dateMonth, dateDay));

                //显示年龄
                commonDialog.remove();
            });
        });
    }

    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }
}
